package collecion.nexd.com.newnexdcollection.util;

import android.content.Context;
import android.os.Environment;
import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import collecion.nexd.com.newnexdcollection.modle.MallInfoObject;
import example.com.nexd.collectionsdk.sdk.utils.Log;

/**
 * Created by xu on 2015/8/14.
 */
public class FileUtil {
    public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值
    private static final int BUFF_SIZE = 8192;

    /**
     * 获取文件指定文件的指定单位的大小
     *
     * @param filePath 文件路径
     * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
     * @return double值的大小
     */
    public static double getFileOrFilesSize(String filePath, int sizeType) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小", "获取失败!");
        }
        return FormetFileSize(blockSize, sizeType);
    }

    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     *
     * @param filePath 文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    public static String getAutoFileOrFilesSize(String filePath) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小", "获取失败!");
        }
        return FormetFileSize(blockSize);
    }

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    private static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    private static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    private static double FormetFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }


    /**
     * 解压缩一个文件
     *
     * @param zipFile    要解压的压缩文件
     * @param folderPath 解压缩的目标目录
     * @throws IOException 当解压缩过程出错时抛出
     */
    public void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
        File desDir = new File(folderPath);
        if (!desDir.exists()) {
            desDir.mkdirs();
        }

        ZipFile zf = new ZipFile(zipFile);
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            InputStream in = zf.getInputStream(entry);
            String str = folderPath + File.separator + entry.getName();
            str = new String(str.getBytes("8859_1"), "GB2312");
            File desFile = new File(str);
            if (!desFile.exists()) {
                File fileParentDir = desFile.getParentFile();
                if (!fileParentDir.exists()) {
                    fileParentDir.mkdirs();
                }
                desFile.createNewFile();
            }
            OutputStream out = new FileOutputStream(desFile);
            byte buffer[] = new byte[1024];
            int realLength;
            while ((realLength = in.read(buffer)) > 0) {
                out.write(buffer, 0, realLength);
            }
            in.close();
            out.close();
        }
    }

    /**
     * 压缩文件/文件夹
     *
     * @param resFile
     * @param zipFilePath
     * @throws Exception
     */


    public static void compressFile(File resFile, String zipFilePath) throws Exception {
        ZipOutputStream zip = new ZipOutputStream(
                new FileOutputStream(new File(zipFilePath + ".zip")));
        compressFile(resFile, zip);
        zip.finish();
        zip.close();
    }

    private static void compressFile(File resFile, ZipOutputStream zipOutputStream) throws Exception {
        if (resFile.isDirectory()) {
            File[] fileList = resFile.listFiles();
            for (File file : fileList) {
                compressFile(file, zipOutputStream);
            }
        } else if (resFile.isFile()) {
            byte buffer[] = new byte[BUFF_SIZE];
            BufferedInputStream in = new BufferedInputStream(
                    new FileInputStream(resFile), BUFF_SIZE);
            zipOutputStream.putNextEntry(new ZipEntry(resFile.getName()));
            int realLength;
            while ((realLength = in.read(buffer)) != -1) {
                zipOutputStream.write(buffer, 0, realLength);
            }
            in.close();
            zipOutputStream.flush();
            zipOutputStream.closeEntry();
        }
    }

    /**
     * 删除目标文件或文件夹
     *
     * @param file
     * @return
     */
    public static boolean deleteFileOrDir(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File childrenFile : files) {
                deleteFileOrDir(childrenFile);
            }
        } else {
            file.delete();
        }
        // 如果是文件夹，删除最外面一层文件夹
        file.delete();
        return true;
    }

    /**
     * 除了主要的文件以外，将缓存文件中的内容都删除掉
     *
     * @param file
     * @return
     */
    public static boolean deleteFileExcJour(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File childrenFile : files) {
                deleteFileExcJour(childrenFile);
            }
        } else {
            if (!"journal".equals(file.getName())) {
                file.delete();
            }
        }
        return true;
    }


    /**
     * 解析XMl文件
     *
     * @return
     * @throws XmlPullParserException
     * @throws IOException
     */
    public static List<MallInfoObject> getMallInfo(Context context, String str_city_name) throws XmlPullParserException, IOException {

        InputStream is = context.getAssets().open(str_city_name + "_mall.xml");
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "UTF_8");

        List<MallInfoObject> list = new ArrayList<>();
        int eventType = parser.getEventType();

        while (eventType != parser.END_DOCUMENT) {

            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("malls")) {
                        break;
                    } else if (parser.getName().equals("mall")) {
                        MallInfoObject mallInfoObject = new MallInfoObject();
                        for (int i = 0; i < parser.getAttributeCount(); i++) {
                            if (parser.getAttributeName(i).equals("py")) {
                                mallInfoObject.seteMallName(parser.getAttributeValue(i));
                            }
                            if (parser.getAttributeName(i).equals("name")) {
                                mallInfoObject.setcMallName(parser.getAttributeValue(i));
                            }
                            if (parser.getAttributeName(i).equals("floor")) {
//                                mallInfo.setFloorNum(parser.getAttributeValue(i));
                            }
                        }
                        list.add(mallInfoObject);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    break;

                default:
                    break;
            }
            eventType = parser.next();
        }
        return list;
    }


    /**
     * 获取缓存文件位置
     * @param context
     * @param uniqueName
     * @return
     */
    public static File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable())
            cachePath = context.getExternalCacheDir().getPath();
        else
            cachePath = Environment.getExternalStorageDirectory().getPath();
        return new File(cachePath + File.separator + uniqueName);
    }
}
